package org.balthie.demo.jdk.util.concurrent.locks;

import java.util.LinkedList;
import java.util.concurrent.locks.LockSupport;

import org.springframework.util.StopWatch;

// 线程阻塞和唤醒的工具

//https://blog.csdn.net/zyzzxycj/article/details/90268381
//LockSupport不需要在同步代码块里 。所以线程间也不需要维护一个共享的同步对象了，实现了线程间的解耦。
//unpark函数可以先于park调用，所以不需要担心线程间的执行的先后顺序。
public class LockSupportDemo {
	static StopWatch sw = new StopWatch();
	
	public static void main(String[] args) throws Exception {
		LinkedList<Thread> startParkTasks = startParkTasks();
		 //不需要主线程休眠，子线程也可以阻塞在park方法
//		sw.start("sleep 1s");
//		Thread.sleep(1000);
//		sw.stop();
		
//		unpark 是给线程打标记，可以在park之前执行
        System.out.println(Thread.currentThread()+ " unpark ");
        sw.start("unpark all");
        startParkTasks.forEach(A->LockSupport.unpark(A));
        sw.stop();
        System.out.println(sw.prettyPrint());
        Thread.sleep(1000);
    }

	public static LinkedList<Thread> startParkTasks() throws InterruptedException
	{
		LinkedList<Thread> taskList = new LinkedList<Thread>();
		sw.start("start 子线程");
        for (int t = 0; t < 100; t++) {
			Thread A = new Thread(() -> {
				System.out.println(Thread.currentThread() + " run ");
				int sum = 0;
				for (int i = 0; i < 10; i++) {
					sum += i;
				}
				System.out.println(Thread.currentThread() + " park ");
				LockSupport.park();
				System.out.println(" print after unpark " + sum);
			});
			taskList.add(A);
			A.start();
		}
		sw.stop();
		return taskList;
	}
}
